import _ from 'lodash';
import { request, METHOD } from '@/utils/request';
import { DATA_CODE_SUCCESS } from '@/utils/consts';

const API_BASE_URL = require('@/services/baseUrl')

const funcNameMapAlias = {
  setWorkHourInfo: 'workHourInfo',
  setPartInfo: 'partInfo',
  setRepairInfo: 'repairInfo'
};

const findOptionByAliasName = ({ formOptions, aliasName }) => {
  const index = formOptions.findIndex((option) => option.aliasName === aliasName);
  const option = formOptions[index];
  const key = `${option.inputName}_${index}`;
  return {
    option,
    index,
    key
  };
};

const formatContractData = (data) => {
  const offset = 1;
  const formatData = {};
  Object.keys(data).forEach((key) => {
    const oriKey = key.match(/\d/)[0];
    formatData[key.replace(/\d/, parseInt(oriKey, 10) + offset)] = data[key];
  });
  return formatData;
};

const dealOption = (formOptions, data, aliasName, disableArrayList = [], enableArrayList = []) => {
  const formOptionsClone = _.cloneDeep(formOptions);
  // eslint-disable-next-line max-len
  const { option, index, key } = findOptionByAliasName({ formOptions: formOptionsClone, aliasName });
  const rowClone = _.cloneDeep(option.rows[0]);
  rowClone.children.forEach((item) => {
    const oriItem = item;
    if (disableArrayList.indexOf(item.aliasName) > -1) {
      oriItem.disabled = true;
    }
    if (enableArrayList.indexOf(item.aliasName) > -1) {
      oriItem.disabled = false;
    }
  });
  const rowsInsArray = [];
  data.forEach(() => {
    rowsInsArray.push(_.cloneDeep(rowClone));
  });
  option.rows = option.rows.filter((r, idx) => idx === 0);
  option.rows.splice(1, 0, rowsInsArray);
  option.rows = _.flatten(option.rows);
  const formData = {};
  option.rows.forEach((rowItem, rowIdx) => {
    if (rowIdx > 0) {
      rowItem.children.forEach((item) => {
        const oriItem = item;
        if (item.type === 'select' && Array.isArray(data[rowIdx - 1][item.aliasName])) {
          oriItem.options = data[rowIdx - 1][item.aliasName];
        } else {
          formData[`${key}_${rowIdx - 1}_${item.inputName}`] = data[rowIdx - 1][item.aliasName] || item.defaultValue || '';
        }
      });
    }
  });
  return {
    option,
    index,
    formData
  };
};

const setOptionAndData = ({
  formOptions, data, funcName, vueComponent, disableArrayList, enableArrayList
}) => {
  const _this = vueComponent;
  const {
    option: updateOption,
    index, formData
  } = dealOption(formOptions, data, funcNameMapAlias[funcName], disableArrayList, enableArrayList);
  _this.$emit('update', updateOption, index);
  const newData = {};
  Object.keys(_this.form).forEach((formKey) => {
    if (formKey.indexOf(updateOption.inputName) === -1) {
      newData[formKey] = _this.form[formKey];
    }
  });
  _this.$set(_this, 'form', newData);
  Object.assign(_this.form, formData);
};

// eslint-disable-next-line max-len
const setWorkHourInfo = ({
  formOptions, data, funcName, vueComponent
}) => {
  const disableArrayList = ['workingHourCode'];
  setOptionAndData({
    formOptions, data: data.dataList, funcName, vueComponent, disableArrayList
  });
};
// eslint-disable-next-line max-len
const setPartInfo = ({
  formOptions, data, funcName, vueComponent
}) => {
  const disableArrayList = [];
  Object.keys(data.dataList[0]).forEach((prop) => {
    if (!Array.isArray(data.dataList[0][prop]) && prop !== 'number') {
      disableArrayList.push(prop);
    }
  });
  const enableArrayList = ['isReasonPart'];
  setOptionAndData({
    formOptions, data: data.dataList, funcName, vueComponent, disableArrayList, enableArrayList
  });
};
// eslint-disable-next-line max-len
const setRepairInfo = async ({
  formOptions, funcName, params, vueComponent
}) => {
  const response = await request(`${API_BASE_URL}/form/work/getRepairRecordListByTypeIdAndVin`, METHOD.GET, params);
  if (response.data.code === DATA_CODE_SUCCESS) {
    setOptionAndData({
      formOptions, data: response.data.data, funcName, vueComponent
    });
  }
};

const setContractType = ({
  option, optIdx, value, vueComponent
}) => {
  const _this = vueComponent;
  const cloneOption = _.cloneDeep(option);
  let contractItem = {};
  cloneOption.rows.forEach((row) => {
    row.children.forEach((item) => {
      if (item.aliasName === 'contractId') {
        contractItem = item;
      }
    });
  });
  if (value === 'customer') {
    contractItem.isHide = false;
  } else {
    contractItem.isHide = true;
  }
  _this.$emit('update', cloneOption, optIdx);
};

const setCarByContract = ({
  data, vueComponent
}) => {
  const _this = vueComponent;
  let contractData = JSON.parse(data);
  contractData = formatContractData(contractData);
  _this.$emit('updateAll', contractData, JSON.parse(data));
};

const calculateDuration = ({ vueComponent, key }) => {
  const _this = vueComponent;
  // 出发时间 zjemgwx
  // 到达时间 hixwrln
  // 救援耗时 jlkobyw
  // 上报日期 crkqrij
  if (_this.form[`${key}_zjemgwx`] && _this.form[`${key}_hixwrln`]) {
    const duration = new Date(_this.form[`${key}_hixwrln`]).getTime() - new Date(_this.form[`${key}_zjemgwx`]).getTime();
    if (duration > 0) {
      _this.form[`${key}_jlkobyw`] = (duration / 1000 / 60 / 60).toFixed(2);
    } else if (duration === 0) {
      _this.form[`${key}_jlkobyw`] = 0;
    } else {
      _this.form[`${key}_jlkobyw`] = 0;
    }
  }
};

const setItemRequiredOrNot = (option, value, params, trueValue) => {
  option.rows.forEach((row) => {
    if (row.children) {
      row.children.forEach((itm) => {
        const oriItm = itm;
        if (params.indexOf(itm.inputName) > -1) {
          const last = oriItm.rules.at(-1);
          oriItm.required = value === trueValue;
          last.required = value === trueValue;
        }
      });
    }
  });
};

const setItemDisabledOrNot = (option, value, params, trueValue, optIdx, vueComponent) => {
  const _this = vueComponent;
  option.rows.forEach((row, rowIdx) => {
    if (row.children) {
      row.children.forEach((itm) => {
        const oriItm = itm;
        if (params.indexOf(itm.inputName) > -1) {
          const last = oriItm.rules.at(-1);
          oriItm.disabled = value !== trueValue;
          oriItm.required = value === trueValue;
          last.required = value === trueValue;
          _this.form[`${option.inputName}_${optIdx}_${rowIdx}_${itm.inputName}`] = '';
        }
      });
    }
  });
};

const setStationService = ({ option, value }) => {
  // 服务站派车牌照号 rvklxgl
  setItemRequiredOrNot(option, value, ['rvklxgl'], '1');
};

const setServiceCar = ({
  option,
  value,
  optIdx,
  vueComponent
}) => {
  setItemDisabledOrNot(option, value, ['wyhovcn', 'kbcgvqj'], '1', optIdx, vueComponent);
};

const setReasonPart = ({
  option, vueComponent, value, item, rowIdx
}) => {
  const _this = vueComponent;
  option.rows.forEach((row, rdx) => {
    if (row.children) {
      row.children.forEach((li) => {
        if (li.inputName === item.inputName && (rowIdx + 1) !== rdx) {
          _this.$set(li, 'disabled', value === '1');
        }
      });
    }
  });
};

const checkRepeat = ({
  option, optIdx, item, vueComponent, value, key, row
}) => {
  const _this = vueComponent;
  let flag = false;
  option.rows.forEach((r, rowIdx) => {
    if (r.children) {
      r.children.forEach((li) => {
        if (
          li.inputName === item.inputName
          && value === _this.form[`${option.inputName}_${optIdx}_${rowIdx - 1}_${li.inputName}`]
          && `${option.inputName}_${optIdx}_${rowIdx - 1}` !== key
        ) {
          _this.$message.error(`${item.label}不能重复!`);
          flag = true;
        }
      });
    }
  });
  if (flag) {
    Object.keys(_this.form).forEach((formKey) => {
      if (formKey.indexOf(key) > -1) {
        _this.form[formKey] = '';
      }
    });
    row.children.forEach((li) => {
      const oriItem = li;
      if (oriItem.type === 'select' && !oriItem.dictionaryType) {
        _this.$set(oriItem, 'options', []);
      }
    });
  }
};

export default {
  setWorkHourInfo,
  setPartInfo,
  setRepairInfo,
  findOptionByAliasName,
  setContractType,
  setCarByContract,
  calculateDuration,
  setStationService,
  setServiceCar,
  setReasonPart,
  checkRepeat,
  funcNameMapAlias
};
